import moment from "moment";
import { NextApiRequest, NextApiResponse } from "next";
import { SolrResponse } from "~/types/solr";

const SOLR_HOST = process.env.SOLR_HOST as string

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const variantId = req.query.id as string
  let price_tier = 'tier1_v2'

  let auth = req.cookies.auth ? JSON.parse(req.cookies.auth) : null
  if (auth?.pricelist) price_tier = auth.pricelist

  if (req.method === 'GET') {
    const queryParams = new URLSearchParams({ q: `id:${variantId}` })
    const response = await fetch(`${SOLR_HOST}/solr/variants/select?${queryParams.toString()}`)
    const data: SolrResponse<any[]> = await response.json()

    if (data.response.numFound === 0) {
      res.status(404).json({ error: 'Variant not found' })
      return
    }

    const variant = await map(data.response.docs[0], price_tier)

    res.status(200).json({ data: variant })
  }
}

const map = async (variant: any, price_tier: string) => {
  const data: any = {}
  const price = variant[`price_${price_tier}_f`] || 0

  data.id = parseInt(variant.id)
  data.parent_id = variant.template_id_i
  data.display_name = variant.display_name_s
  data.image = variant.image_s
  data.name = variant.name_s
  data.default_code = variant.default_code_s
  data.price = { discount_percentage: 0, price, price_discount: price }
  data.manufacture = {manufacture_name: variant.manufacture_name_s, manufacture_id:variant.manufacture_id_i}

  return data
}

const checkIsFlashsale = (variant: any) => {
  const endDateStr = variant.flashsale_end_date_s || null
  if (!endDateStr) return false

  const now = moment()
  const endDate = moment(endDateStr, 'YYYY-MM-DD HH:mm:ss')

  return variant.flashsale_id_i > 0 && now.isSameOrBefore(endDate)
}